<?php

/* 
 * To change this license header, choose License Headers in Project Properties.
 * To change this template file, choose Tools | Templates
 * and open the template in the editor.
 */
namespace app\admin\controller;
use app\admin\model\Cate as CateModel;
use app\admin\model\Article as ArticleModel;
use think\File;
class Cate extends Common{
      protected $beforeActionList = [
        'delson'=>['only'=>'del'],
    ];
    
    
    public  function lst(){
        $cates=new CateModel();
        $res=$cates->sort();
        $this->assign("res",$res);
        if(request()->isPost()){
            $data=input("post.");
            foreach ($data as $k => $v){
              $cates->update(["id"=>$k ,"sort"=>$v]);
            }
            return $this->success("更新成功",'lst');
        }
        return view();
    }


    public function add(){
         $cate=new CateModel();
         $cates=$cate->sort();
         $this->assign("cates",$cates);
        if(request()->isPost()){
            $data= input('post.');
            $res=$cate->save($data);
            if($res){
                return $this->success("添加成功","lst");
             }
            else {
                 return $this->error("添加失败","add");
             }
        }
        return view();
    }
    
    public function edit(){
        $id=input('id');
        $cate=new CateModel();
        $res=$cate->where("id",$id)->find();
        $cates=$cate->sort();


        if(request()->isPost()){
            $data=input();
            $res=$cate->update($data);
            if($res){
                return $this->success("更新成功","lst");
            }else{
                return $this->success("更新失败","lst");
            }
        }
        $this->assign("res",$res);
        $this->assign("cates",$cates);
        return view();
    }

    public function  del(){
        $id=input("id");
        $cate=new CateModel();
        $res=$cate->where("id",$id)->delete();
        if($res){
            return $this->success("删除成功",'lst');
        }else{
            return $this->error("删除失败",'lst');
        }

    }
    protected  function delson(){
        $cateid=input("id");
        $cate=new CateModel();
        $sonsid=$cate->getChildrenId($cateid);
        $all=$sonsid;
        $all[]=$cateid;
        foreach ($all as $k=> $v){
            $article=new ArticleModel();
             $article->destroy($v);  
            
            
        }
        
        foreach ($sonsid as $k => $v){
            $res=$cate->where("id",$v)->delete();
            if(!$res){
                return $this->error("删除子栏目时发生错误",'lst');
            }
        }
    }
    
    //删除栏目时，如果删除的是文章
}
